const Service = require("egg").Service;
const { timestamp } = require("../utils/tools");

class RoleService extends Service {
  // 角色信息
  async info_by_role_name(role_name) {
    const result = await this.app.mysql.get("role", {
      role_name,
    });
    return result;
  }

  // 新增角色
  async add(role_name) {
    const user = await this.app.mysql.get("role", {
      role_name,
    });
    const tem = {};
    if (user) {
      tem.type = "fail";
      tem.message = "该角色已经存在!";
    } else {
      const result = await this.app.mysql.insert("role", {
        role_name,
        create_time: Date.now(),
        update_time: Date.now(),
      });
      tem.type = "success";
      tem.message = "新增成功";
    }

    return tem;
  }

  // 修改角色
  async edit({ id, role_name }) {
    const result = await this.app.mysql.update("role", {
      id,
      role_name,
      update_time: Date.now(),
    });
    return result;
  }

  // 查询角色
  async list({ keyword = "", page = 1, page_size = 10, order = "id_desc" }) {
    const [columns, mode] = order.split("_");
    const offset = (page - 1) * page_size || 0;
    const size = parseInt(page_size);
    const data = await this.app.mysql.query(
      "select * from role where role_name like ? order by ? ? limit ?, ? ;",
      [`%${keyword}%`, columns, mode, offset, size]
    );
    const total = await this.app.mysql.count("role");
    return {
      data,
      total,
    };
  }

  // 删除角色
  async delete(id) {
    const result = await this.app.mysql.delete("role", { id: id + "" });
    return result;
  }

  // 角色分配菜单
  async add_menu({ id, menus = [] }) {
    const menus_id = menus.join(",");
    const menus_result = await this.app.mysql.query(
      `select * from menu where id in (${menus_id});`
    );
    const route_menus = menus_result
      .filter((item) => item.type === "route" && item.code !== "")
      .map((item) => item.code)
      .join();
    const btn_menus = menus_result
      .filter((item) => item.type === "btn" && item.code !== "")
      .map((item) => item.code)
      .join();

    const role_result = await this.app.mysql.update("role", {
      id,
      routes: route_menus,
      btns: btn_menus,
    });

    return role_result;
  }
}

module.exports = RoleService;
